<?php
use system\core\Config;
use system\core\Registry;

/**
 * Returns a well formed form start tag
 * 
 * @param string $action
 * @return string
 */
function form_open( $action = '', $method = 'post' )
{
    if ( ! preg_match('#^https?://#i', $action) )
    {
        $baseUrl = Config::get('config', 'base_url');
    }
    else
    {
        $baseUrl = '';
    }

    return '<form action="' . $baseUrl . $action . '" method="' . $method . '" accept-charset="utf-8">' . PHP_EOL;
}


/**
 * Returns a closing form tag
 *  
 * @return string
 */
function form_close()
{
    return '</form>' . PHP_EOL;
}


/**
 * Set the value for form elements
 * 
 * @param string $name
 * @param string $default
 * @return string
 */
function set_value( $name, $default = '' )
{
    if ( isset($_REQUEST[$name]) )
    {
        return $_REQUEST[$name];
    }
    return $default;
}

/**
 * Get all validation errors
 */
function validation_errors( $group = 'default', $prefix = '<p>', $suffix = '</p>' )
{
    $output = '';

    $errors = Registry::get('form_validation_errors');

    if ( isset($errors[$group]) && count($errors[$group]) > 0 )
    {
        $output .= $prefix;
        foreach ( $errors[$group] as $error )
        {
            $output .= $error . '<br />' . PHP_EOL;
        }
        $output .= $suffix;
    }

    return $output;
}

/**
 * Get all validation errors
 */
function form_error( $field, $group = 'default' )
{
    $errors = Registry::get('form_validation_errors');

    if ( isset($errors[$group][$field]) && count($errors[$group][$field]) > 0 )
    {
        return '<span class="g-form-error">' . $errors[$group][$field] . '</span>';
    }
}